<template>
  <div class="product-inspection">
    <!-- 产品检验 -->
    <div class="inspect-search">
      <search-form
        :search-fields="form"
        :search-form="forms"
        :rules="rules"
        @handle-search="handleSearch"
      >
        <search-sites
          :site-name="form.station"
          @change-site="
            (n) => {
              form.station = n;
            }
          "
        />
      </search-form>
    </div>
    <div class="inspect-display">
      <div class="inspect-btns">
        <el-button-group class="inspect-display-btns">
          <el-button
            class="inspect-display-btn"
            :type="mode === '0' ? 'primary' : 'default'"
            size="mini"
            @click="changeMode('0')"
          >
            表格展示
          </el-button>
          <el-button
            class="inspect-display-btn"
            :type="mode === '1' ? 'primary' : 'default'"
            size="mini"
            @click="changeMode('1')"
          >
            图形展示
          </el-button>
        </el-button-group>
        <el-button
          class="inspect-download-btn"
          type="success"
          size="mini"
          v-if="mode === '0'"
          @click="handleDownload"
        >
          下 载
        </el-button>
      </div>
      <!-- 表格 -->
      <div class="inspect-table-wrapper" v-show="mode === '0'">
        <div class="inspect-table-title">
          {{ tableTitle }}
        </div>
        <datagrid
          max-height="100%"
          :data-list="inspectList"
          :columns="columns"
          :total="total"
          :current-page="1"
          :page-size="5"
          :loading="loading"
        >
          <el-table-column
            align="center"
            label="检验模式"
            prop="pattern"
            slot="pattern"
            :formatter="formatPattern"
          />
        </datagrid>
        <!-- 起报时间 -->
        <div class="inspect-time-range">
          起报时间：{{ form.startTime }} ~ {{ form.endTime }}
        </div>
      </div>
      <!-- 图形 -->
      <div class="inspect-chart-wrapper" v-show="mode === '1'">
        <!-- <el-button-group class="inspect-chart-btns">
          <el-button
            size="mini"
            class="inspect-chart-btn"
            :class="{ 'is-active': chartType === 'bar' }"
            @click="changeChartType('bar')"
          >
            柱状图
          </el-button>
          <el-button
            size="mini"
            class="inspect-chart-btn"
            :class="{ 'is-active': chartType === 'line' }"
            @click="changeChartType('line')"
          >
            折线图
          </el-button>
        </el-button-group> -->
        <div class="inspect-chart-box">
          <chart :c-option="option" ref="myChart" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import SearchForm from '@/components/SearchForm'
import Datagrid from '@/components/Datagrid'
import SearchSites from '@/components/SearchSites'
import Chart from '@/components/Chart'

import dayjs from 'dayjs'
import { checkType, order, patterns, methods, hours_f } from '@/utils/constant.js'

import { downFilePost, postAction } from '@/api/action';
export default {
  name: 'ProductDisplay',
  components: { SearchForm, Datagrid, SearchSites, Chart },
  data() {
    return {
      urls: {
        inspect: '/api/checkout/getCheckout',
        download: '/api/checkout/exportXlChecoutData',
      },
      total: 0,
      loading: false,
      inspectList: [],
      form: {
        type: '0', // 检验类型
        startTime: dayjs().subtract(7, 'day').format('YYYY-MM-DD'), // 开始时间
        endTime: dayjs().format('YYYY-MM-DD'), // 结束时间
        station: '梧州市', // 站名
        checoutTime: '08', // 起报时间
        timeLiness: '12', // 累累积雨量
        order: '0.1', // 检验阈值
        methond: '0', // 检验方法
      },
      forms: [{
        label: '检验类型',
        field: 'type',
        type: 'select',
        options: checkType,
      }, {
        label: '开始时间',
        field: 'startTime',
        type: 'date'
      }, {
        label: '结束时间',
        field: 'endTime',
        type: 'date'
      }, {
        label: '站点/区域',
        field: 'station',
        type: 'select',
        slot: true,
      }, {
        label: '起报时间',
        field: 'checoutTime',
        type: 'select',
        options: hours_f,
      }, {
        label: '累积雨量',
        field: 'timeLiness',
        type: 'select',
        options: [{
          label: '12',
          value: '12',
        }],
      }, {
        label: '检验阈值',
        field: 'order',
        type: 'select',
        options: order,
      }, {
        label: '检验方法',
        field: 'methond',
        type: 'select',
        options: methods,
      },
      ],
      columns: [
        {
          label: '检验模式',
          prop: 'pattern',
          slot: true,
        }, {
          label: '12时效',
          prop: 'time12'
        }, {
          label: '24时效',
          prop: 'time24'
        }, {
          label: '36时效',
          prop: 'time36'
        }, {
          label: '48时效',
          prop: 'time48'
        }, {
          label: '60时效',
          prop: 'time60'
        }, {
          label: '72时效',
          prop: 'time72'
        }
      ],
      rules: {
        type: [{ required: true }],
        startTime: [{ required: true }],
        endTime: [{ required: true }],
        station: [{ required: true }],
        checoutTime: [{ required: true }],
        timeLiness: [{ required: true }],
        order: [{ required: true }],
        methond: [{ required: true }],
      },
      mode: '0', // 0 表格 1 图形
      chartType: 'bar',
      option: {},
    }
  },
  computed: {
    tableTitle() {
      const method = this.forms[this.forms.length - 1].options[+this.form.methond].label;
      return `${this.form.station}逐12小时降水预报${method}`;
    },
    formatFileName() {
      const { station, startTime, endTime, checoutTime, methond } = this.form;
      return `${station}-${startTime}至${endTime} ${checoutTime}时${methods[methond].label}检验数据`;
    },
  },
  watch: {
    formatFileName: {
      handler(newV, oldV) {
        // 更新图形的title，即下载的图片名
        this.option.imgName = newV;
        // this.$nextTick(() => {
        //   this.$refs.myChart.updateChart();
        // })
      },
      immediate: true,
    }
  },
  created() {
    this.handleSearch();
  },
  methods: {
    async getData() {
      this.loading = true;
      await postAction(this.urls.inspect, this.form).then(res => {
        console.log('产品展示', res);
        if (res.msg === '查询成功，但无数据') {
          this.$message(res.msg);
          this.loading = false;
        }
        this.inspectList = [];
        this.option.series = [];
        this.option.xData = [];
        if (res.msg === '成功' && res.objects) {
          this.option.xData = ['12', '24', '36', '48', '60', '72'];
          this.inspectList = res.objects;
          this.loading = false;
        }
        this.formatChartData(res.objects);
      })
      this.loading = false;
    },
    // 格式化检验模式
    formatPattern(row, column, cell) {
      return patterns[+row[column.property]].label;
    },
    // 处理图形数据
    formatChartData(obj) {
      if (obj) {
        obj.map(item => {
          const sData = [];
          for (let index = 0; index < this.option.xData.length; index++) {
            sData.push(item['time' + this.option.xData[index]]);
          }
          this.option.series.push({
            name: patterns[+item.pattern].label,
            type: this.chartType,
            barWidth: 20,
            data: sData,
            label: { show: true },
          });
        })
        this.option.yName = this.forms[this.forms.length - 1].options[+this.form.methond].label;
      }
      this.$refs.myChart && this.$refs.myChart.updateChart();
    },
    // 搜索
    handleSearch() { this.getData(); },
    // 切换展示模式
    changeMode(type) {
      this.mode = type;
      setTimeout(() => {
        this.$refs.myChart.resizeChart();
      }, 0);
    },
    // 切换图表类型
    changeChartType(type) {
      this.chartType = type;
      const series = this.option.series;
      this.option.series = [];
      for (let index = 0; index < series.length; index++) {
        series[index].type = type;
      }
      this.option.series = series;
      console.log('series', this.option.series);
    },
    // 下载
    handleDownload() {
      // const { station, startTime, endTime, checoutTime, methond } = this.form;
      // const fileName = `${station}站${startTime}至${endTime} ${checoutTime}时${methond}检验数据`;
      const fileName = this.formatFileName + '.xls';
      console.log(fileName);
      // 0-下载   1-离线
      downFilePost(this.urls.download, this.form).then(res => {
        console.log('下载', res);
        if (res.status === 200) {
          // const fileName = decodeURI(escape(res.headers['content-disposition'].split('filename=')[1]));
          const { data } = res;
          if (!data) {
            this.$message.warning('文件下载失败');
            return;
          }

          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], { type: 'application/text' }), fileName);
          } else {
            const url = window.URL.createObjectURL(new Blob([data], { type: 'application/text' }));
            const link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.setAttribute('download', fileName);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link); // 下载完成移除元素
            window.URL.revokeObjectURL(url); // 释放掉blob对象
          }
        }
      })
    },
  }
}
</script>

<style lang="scss">
.product-inspection {
  height: 100%;
  display: flex;
  flex-direction: column;
  // .inspect-search {
  //   .search-form-wrapper {
  //     padding: 0 1em;
  //   }
  // }
  .datagrid-table-wrapper {
    padding: 0 2em;
  }
  // .datagrid-table {
  //   max-height: calc(100% - 145px);
  // }
  .inspect-table-title,
  .inspect-time-range {
    height: 30px;
    font-family: "SourceHanSansCN";
  }
  .inspect-table-title {
    font-size: 16px;
    text-align: center;
    color: rgb(51, 133, 255);
  }
  .inspect-time-range {
    padding: 0 2em;
    font-size: 14px;
    line-height: 30px;
    text-align: right;
    color: rgb(102, 102, 102);
  }
}
</style>